package com.ry.est.service.impl;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.ry.est.constants.Constants;
import com.ry.est.constants.ResultEnum;
import com.ry.est.dao.UsersDao;
import com.ry.est.entity.Users;
import com.ry.est.exception.BussinessException;
import com.ry.est.service.SmsVerifyCodeService;
import com.ry.est.service.UserService;
import com.ry.est.vo.TokenVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author ry
 * @since 2021-11-01 17:10
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UsersDao usersDao;

    @Autowired
    private SmsVerifyCodeService smsVerifyCodeService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Users findById(Long id) {
        return usersDao.selectByPrimaryKey(id);
    }

    @Override
    public Users findByOpenId(String openid) {
        Users users = usersDao.selectByOpenId(openid);
        return users;
    }

    @Override
    public Users register(Users users) {
        usersDao.insertSelective(users);

        return users;
    }

    @Override
    public TokenVo login(Users users) {
        return null;
    }

    /**
     * 使用短信验证码登录
     * @param phone
     * @param sms
     * @return
     */
    @Override
    public Users loginBySms(String phone, String sms) {
        //根据手机号获取验证码
        String loginVerifyCode = smsVerifyCodeService.getLoginVerifyCode(phone);
        //对比验证码
        //逻辑...todo
        if (Objects.isNull(loginVerifyCode) || !Objects.equals(loginVerifyCode,sms)){
            throw new BussinessException(ResultEnum.FAIL_VERIFY);
        }
        //验证码不正确，抛出异常
        //验证码正确，删除验证码
        smsVerifyCodeService.removeLoginVerifyCode(phone);
        //到数据库中查询用户信息是否存在
        Users users = usersDao.selectByAccount(phone);
        //如果不存在就自动注册
        if (Objects.isNull(users)){
            users = new Users();
            users.setAccount(phone);
            users.setUserName(phone);
            users.setCreatedTime(new Date());
            users.setIsDelete(Constants.EST_NOT);
            //
            users.setIsAuthentication(Constants.EST_NOT);

            usersDao.insert(users);
        }

        return users;
    }
}
